window.ngPromiseHandler = function (resolve, reject) {
    return function (data) {
        if (data.code === 0) {
            resolve(data.data);
        } else {
            reject(data.data);
        }
    }
};
window.formHeaders = {'Content-Type': 'application/x-www-form-urlencoded'};
window.randomStr = function (n) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < n; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
};

function isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase();
    return ua.indexOf('micromessenger')>=0;
}

//var viewPortScale = 1;
//var dpr = window.devicePixelRatio;
//
//var detectBrowser = function(name) {
//    if(navigator.userAgent.toLowerCase().indexOf(name) > -1) {
//        return true;
//    } else {
//        return false;
//    }
//};
//
//if(detectBrowser('ucbrowser') ||
//    dpr === 3  ||
//    detectBrowser('mqqbrowser')) {
//    document.getElementById('viewport').setAttribute(
//        'content',
//        'width=device-width',
//    'minimum-scale=1',
//        'initial-scale=' + viewPortScale);
//} else {
//    document.getElementById('viewport').setAttribute(
//        'content',
//        'target-densitydpi=device-dpi',
//    'width=device-width',
//        'minimum-scale=1',
//        'initial-scale=' + viewPortScale);
//}

window.WebApp = {
    currentUser: {},
    Roles: {
        ADMIN: 'admin',
        push_ADMIN: 'push_admin',
        SHOP_OWNER: 'shop_owner',
        SHOP_CHECKER: 'shop_checker',
        PRODUCT_CHECKER: 'product_checker'
    }
};

var app = angular.module('mvcRestBaseApp', [
    'ngRoute',
    'ngResource',
    'ngSanitize',
    'ui.bootstrap',
    "checklist-model",
    'mvcApp.home',
    'mvcApp.category-admin',
    'mvcApp.shop-admin',
    'mvcApp.login',
    'mvcApp.register',
    'mvcApp.shop-list',
    'mvcApp.shop',
    'mvcApp.product',
    'mvcApp.my-favorites',
    'mvcApp.mobile-settings',
    'mvcApp.change-password',
    'mvcApp.user-admin',
    'mvcApp.search-shops',
    'mvcApp.search-products',
    'mvcApp.push-admin',
    'mvcApp.help-phone-page-editor',
    'mvcApp.renew-about-page-editor',
    'mvcApp.one-card-about-page-editor'
]).config(['$compileProvider', '$routeProvider', function ($compileProvider, $routeProvider) {
    $routeProvider
        .otherwise({
            redirectTo: '/home'
        });
}]).run(['$rootScope', '$http', '$location', '$sce', 'User',
    function ($rootScope, $http, $location, $sce, User) {
        if (getParameterByName('__wechat_oauth')) {
            window.location.href = '/#' + getParameterByName('__wechat_oauth');
            return;
        }
        $rootScope.currentUser = WebApp.currentUser;
        $http.get('/wechatshop/profile')
            .success(function (data) {
                if (data.code === 0) {
                    _.extend(WebApp.currentUser, data.data);
                } else {
                    if (window.location.href.indexOf('/login') < 0) {
                        window.location.href = '#/login';
                    }
                }
            });
        //if (isWeiXin()) {
        //    User.getWechatLoginUrl()
        //        .then(function (url) {
        //            window.location.href = url;
        //        }).catch(function (err) {
        //            alert(err);
        //        });
        //}
        $rootScope.isInWechat = isWeiXin();
        $rootScope.hasAnyRoles = function () {
            // whether has any roles in the arguments
            var roleNames = _.toArray(arguments);
            if (!$rootScope.currentUser || !$rootScope.currentUser.roles) {
                return;
            }
            for (var i = 0; i < $rootScope.currentUser.roles.length; ++i) {
                var role = $rootScope.currentUser.roles[i];
                for (var j = 0; j < roleNames.length; ++j) {
                    if (roleNames[j] === role.name) {
                        return true;
                    }
                }
            }
            return false;
        };
        $rootScope.goToBack = function () {
            window.history.back();
        };
        $rootScope.to_trusted = function (html_code) {
            return $sce.trustAsHtml(html_code);
        };
        $rootScope.goToTop = function () {
            var $container = $(".container.content");
            $container.animate({scrollTop: 0}, 1000);
        };
        $rootScope.goToBottom = function () {
            var $container = $(".container.content");
            $container.animate({scrollTop: $container.height()}, 1000);
        };
        $rootScope.goToShopById = function (shopId) {
            $location.path('/shop/' + shopId);
        };
    }]);

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });
                event.preventDefault();
            }
        });
    };
});

setInterval(function () {
    var height = document.documentElement.clientHeight;
    $(".content.container").css({
        height: (height - $(".footer-bar").height()) + 'px'
    });
}, 500);
